package com.doctor.ui.homedoctor;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map.Entry;

import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

import com.doctor.adapter.PatientFileAdapter;
import com.doctor.adapter.PatientFileAdapter.HomeDoctorAdapterCallback;
import com.doctor.bean.PatientDiseaseCountTimeBean;
import com.doctor.bean.PatientFileBean;
import com.doctor.bean.UserBean;
import com.doctor.comm.ConstConfig;
import com.doctor.comm.DialogHelper;
import com.doctor.comm.FileHelper;
import com.doctor.comm.DialogHelper.DialogSelectCallback;
import com.doctor.comm.DialogHelper.NoticeDialogCallback;
import com.doctor.comm.FragmentHelper;
import com.doctor.comm.LoadingTip;
import com.doctor.comm.MyApplication;
import com.doctor.comm.URLConfig;
import com.doctor.database.DbOperator;
import com.doctor.net.GetDataThread;
import com.doctor.net.GetDataThread.DataCallback;
import com.doctor.net.NetUtil;
import com.doctor.net.RequestParams;
import com.doctor.net.ThreadPoolManager;
import com.doctor.ui.BaseFragment;
import com.doctor.ui.R;
import com.doctor.view.PullToRefreshListView;
import com.doctor.view.PullToRefreshListView.OnRefreshListener;
import com.google.gson.Gson;

public class PatientFileFrag extends BaseFragment{

	/**
	 * 患者档案
	 */
	
	private Context context;
	private String[] operation={"修改","删除","取消"};
	private PullToRefreshListView listView;
	private PatientFileAdapter adapter;
	private View listFoot;
	private TextView footMore;
	private ProgressBar footProgress;
	//从第1行开始查询
	private int fromRow=0;
	private AddPatientFileFrag addPatientFileFrag;
	private ModifyPatientFileFrag modifyPatientFileFrag;
	private LookPatientFileFrag lookPatientFileFrag;
	private List<PatientFileBean> beanList=new ArrayList<PatientFileBean>();
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		context=getActivity();
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view=inflater.inflate(R.layout.patient_file, container, false);
		initiaView(view);
		
		return view;
	}
	
	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}
	
	@Override
	protected void initiaView(View view) {
		// TODO Auto-generated method stub
		fromRow=0;
		view.findViewById(R.id.downloadBtn).setOnClickListener(onClick);
		view.findViewById(R.id.uploadBtn).setOnClickListener(onClick);
		view.findViewById(R.id.addBtn).setOnClickListener(onClick);
		
		listView=(PullToRefreshListView) view.findViewById(R.id.listView);
		listFoot=View.inflate(getActivity(), R.layout.listview_footer, null);
		footMore=(TextView) listFoot.findViewById(R.id.listview_foot_more);
		footProgress=(ProgressBar) listFoot.findViewById(R.id.listview_foot_progress);
		// 添加底部视图 必须在setAdapter前
		listView.addFooterView(listFoot);
				
		adapter=new PatientFileAdapter(context,beanList,new HomeDoctorAdapterCallback() {			
			@Override
			public void onCallPhone(String phoneNumber) {
				// TODO Auto-generated method stub
				FileHelper.dialPhone(getActivity(), context, phoneNumber);
			}
		});
		listView.setAdapter(adapter);
		listView.setOnScrollListener(new OnScrollListener() {			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
				listView.onScrollStateChanged(view, scrollState);		
				if (adapter.getCount()==0) {
					return;
				}
				//判断是否滚动到底部
				boolean scrollEnd=false;
				try {
					if (view.getPositionForView(listFoot)==view.getLastVisiblePosition()) {
						scrollEnd=true;
					}
				} catch (Exception e) {
					scrollEnd=false;
					e.printStackTrace();					
				}
				
				if (scrollEnd && scrollState==SCROLL_STATE_TOUCH_SCROLL) {
					//下拉刷新
					footMore.setText(R.string.loading_data);
					footProgress.setVisibility(View.VISIBLE);
					footMore.setVisibility(View.VISIBLE);
					fromRow=adapter.getCount();
					freshData(fromRow);
				}	
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
				listView.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);
			}
		});
		
		listView.setOnRefreshListener(new OnRefreshListener() {			
			@Override
			public void onRefresh() {
				// TODO Auto-generated method stub
				//上拉刷新
				listView.onRefreshComplete();
				fromRow=0;
				freshData(fromRow);
			}
		});
		
		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				final PatientFileBean bean=(PatientFileBean) arg1.getTag(R.id.bean_tag);
				lookPatientFileFrag=null;
				lookPatientFileFrag=new LookPatientFileFrag();
				Bundle bundle=new Bundle();
				bundle.putSerializable(ConstConfig.BEAN, bean);
				lookPatientFileFrag.setArguments(bundle);
				FragmentTransaction transaction=getActivity().getSupportFragmentManager().beginTransaction();
				FragmentHelper.setFragSwitchAnimation(transaction);
				transaction.replace(R.id.frag_container, lookPatientFileFrag).addToBackStack(null).commit();
				
			}
		});
		
		listView.setOnItemLongClickListener(new OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				// TODO Auto-generated method stub
				if (arg1==listFoot) {
					//点击底部栏无效
					return true;
				}
				
				final PatientFileBean bean= (PatientFileBean) arg1.getTag(R.id.bean_tag);
				//减去header占去的一个位置才是item的真实位置
				final int beanPosition=arg2-1;
				
				DialogHelper.selectDialog(context, null, operation, new DialogSelectCallback() {
					@Override
					public void onDialogSelected(int position1) {
						// TODO Auto-generated method stub
						if (position1==0) {
							//修改
							modifyPatientFileFrag=null;
							modifyPatientFileFrag=new ModifyPatientFileFrag();
							Bundle bundle=new Bundle();
							bundle.putSerializable(ConstConfig.BEAN, bean);
							modifyPatientFileFrag.setArguments(bundle);
							FragmentTransaction transaction=getActivity().getSupportFragmentManager().beginTransaction();
							FragmentHelper.setFragSwitchAnimation(transaction);
							transaction.replace(R.id.frag_container, modifyPatientFileFrag).addToBackStack(null).commit();
							
						} else if (position1==1) {
							//删除前确定是否有相关病历记录
							int count=DbOperator.getInstance(context).selectDiseaseCount(bean.getId());
							if (count>0) {
								DialogHelper.showConfirmDialog(context, bean.getName()+"有"+count+"条病历资料，请先删除相关的病历记录！");
								return;
							}
							
							DialogHelper.noticeDialog(context, "删除后不可恢复，确定要删除？", new NoticeDialogCallback() {								
								@Override
								public void onClicked(int position2) {
									// TODO Auto-generated method stub
									if (position2==1) {
										//删除
										int row=DbOperator.getInstance(context).deleteData(ConstConfig.PATIENT_FILE_TABLE, bean.getId());
										String deleteResult=row>0?"成功！":"失败！";
										Toast.makeText(context, "删除"+deleteResult, Toast.LENGTH_SHORT).show();
										if (row>0) {
											final int cid = adapter.getItem(beanPosition).getCid();
											final int id = adapter.getItem(beanPosition).getId();
											//更新adapter数据
											adapter.removeBean(beanPosition);
											if (cid > 0) {
												//记录到删除表里
												ThreadPoolManager.getInstance().addTask(new Runnable() {
													@Override
													public void run() {
														// TODO Auto-generated method stub
														ContentValues cv = new ContentValues();
														cv.put("_id", id);
														cv.put("_cid", cid);
														DbOperator.getInstance(MyApplication.getInstance()).insertData(ConstConfig.DELETED_PATIENT_FILE_TABLE, cv);
													}
												});
											}
										}
									}
								}
							});
						}
					}
				});
				return true;
			}
		});
		freshData(fromRow);			
	}
	
	private void freshData(final int fromRow){
		if (fromRow<=0) {
			adapter.clear();
			//上拉刷新后id从头开始计数
			this.fromRow=0;
			adapter.notifyDataSetChanged();
		}
		
		new Thread() {
			public void run() {
				try {
					sleep(DbOperator.delayTime);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				final List<PatientFileBean> list=DbOperator.getInstance(context).selectPatientFileData(fromRow);
				getActivity().runOnUiThread(new Runnable() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						if (list!=null && list.size()>0) {
							for (PatientFileBean bean : list) {
								adapter.addBean(bean);
							}
							adapter.notifyDataSetChanged();
						}
						footMore.setText(R.string.more);
						footMore.setVisibility(View.GONE);
						footProgress.setVisibility(View.GONE);
					}
				});
			}
		}.start();	
	}
	
	
	private View.OnClickListener onClick = new View.OnClickListener() {		
		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			switch (arg0.getId()) {
			case R.id.uploadBtn:  //上传
				inputPwd(0);
				break;
				
			case R.id.downloadBtn:  //下载备份数据
				inputPwd(1);
				break;

			case R.id.addBtn:  //添加
				addPatientFileFrag=null;
				addPatientFileFrag=new AddPatientFileFrag();
				FragmentTransaction transaction=getActivity().getSupportFragmentManager().beginTransaction();
				FragmentHelper.setFragSwitchAnimation(transaction);
				transaction.replace(R.id.frag_container, addPatientFileFrag).addToBackStack(null).commit();
				break;
				
			default:
				break;
			}
		}
	};
	
	
    /**
     * 上传下载前弹出输入密码对话框
     * @param type 类型(0为上传1为下载)
     */
    private void inputPwd(final int type) {
    	if (!NetUtil.hasNetwork(context)) {
			LoadingTip.showToast(context, "请连接网络！");
			return;
		}
    	
    	AlertDialog.Builder builder = new AlertDialog.Builder(context, R.style.common_dialog);
    	builder.setIcon(R.drawable.alert_icon);
    	builder.setTitle(type == 0 ? "上传备份数据验证" : "下载备份数据验证");
    	builder.setCancelable(false);
    	View view = View.inflate(context, R.layout.verify_account_pwd_dialog, null);
    	final TextView account = (TextView) view.findViewById(R.id.account);
    	final EditText pwd = (EditText) view.findViewById(R.id.pwd);
    	
    	final UserBean user = MyApplication.getInstance().getUserBean();
    	
    	if (user != null && user.getUsername() != null) {
    		account.setText("医师宝序号：" + user.getUsername());
		}
    	
    	builder.setView(view);
    	builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				// TODO Auto-generated method stub
				final String account_txt = (user != null && user.getUsername() != null) ? user.getUsername() : null;
				final String pwd_txt = pwd.getText().toString();
				if (account_txt == null || account_txt.trim().length() <=0 || pwd_txt == null || pwd_txt.trim().length() <= 0) {
					LoadingTip.showToast(context, "请输入密码！");
					return;
				}
				if (!NetUtil.hasNetwork(context)) {
					LoadingTip.showToast(context, "请连接网络！");
					return;
				}
				
				if (type == 0) {
					uploadData(account_txt, pwd_txt);
				} else {
					if (!NetUtil.hasNetwork(context)) {
						LoadingTip.showToast(context, "请连接网络！");
						return;
					}
					
					//弹出提示上次备份数据时间对话框
					LoadingTip.showDialog(context, null);
					HashMap<String, String> map = new HashMap<String, String>();
					map.put("account", account_txt);
					map.put("pwd", pwd_txt);
					map.put("serial_number", FileHelper.getImieStatus(MyApplication.getInstance()));
					RequestParams request = new RequestParams(URLConfig.PATIENT_DISEASE_COUNT_TIME_URL, context, map, String.class);
					GetDataThread.getInstance(context).getDataFromServer(ConstConfig.POST, "UTF-8", request, new DataCallback<String>() {
						@Override
						public void processData(String paramObject, boolean paramBoolean) {
							// TODO Auto-generated method stub
							LoadingTip.hideDialog();
							int patientFileCount = 0, diseaseRecordCount = 0;
							String updateTime = null;
							String errorString = null;
							if (paramObject != null && paramObject.length() > 0) {
								paramObject = paramObject.trim();
								if (paramObject.length() > 0 && paramObject.startsWith("{") && paramObject.endsWith("}")) {
									try {
										Gson gson = new Gson();
										PatientDiseaseCountTimeBean bean = gson.fromJson(paramObject, PatientDiseaseCountTimeBean.class);
										if (bean != null) {
											patientFileCount = bean.getPatient_count() != null ? bean.getPatient_count() : 0;
											diseaseRecordCount = bean.getCase_count() != null ? bean.getCase_count() : 0;
											updateTime = bean.getAddtime();
										} else {
											errorString = "出错了！";
										}
									} catch (Exception e) {
										// TODO: handle exception
										e.printStackTrace();
										errorString = "出错了！";
									}
								} else {
									if ("不存在该账户".equals(paramObject) || "用户名或密码错误".equals(paramObject) || "平板序列号错误".equals(paramObject)) {
										errorString = "请输入正确的密码！";
									} else if ("账号已过有效期！请充值或者联系客服".equals(paramObject)) {
										errorString = "帐号已过有效期！请充值！\n充值电话：医师宝客服中心 18702537275 18702613050";
									} else if ("账号未激活请注册".equals(paramObject)) {
										errorString = "帐号未激活，点击确定前往医师谷网站进行注册！\n如需帮助请联系医师宝客服中心 18702537275 18702613050";
									} else {
										errorString = "出错了！";
									}
								}
							} else {
								errorString = "出错了！";
							}
							final AlertDialog.Builder builder = new AlertDialog.Builder(context, R.style.common_dialog);
							builder.setTitle("提示");
							builder.setIcon(R.drawable.alert_icon);
							String info = errorString != null ? errorString : "已备份数据共" + (patientFileCount + diseaseRecordCount) + "条" + 
									(updateTime == null || updateTime.length() <= 0 ? "" : "，\n上次备份时间" + updateTime);
							builder.setMessage(info);
							final String finalErrorString = errorString;
							final boolean showCancelBtn = "帐号未激活，点击确定前往医师谷网站进行注册！\n如需帮助请联系医师宝客服中心 18702537275 18702613050".equals(finalErrorString);
							if (showCancelBtn) {
								builder.setNegativeButton("取消", null);
							}
							builder.setPositiveButton("确定", new OnClickListener() {
								public void onClick(DialogInterface arg0, int arg1) {
									// TODO Auto-generated method stub
									if (finalErrorString != null) {
										if (showCancelBtn) {
											Intent intent = new Intent();        
									        intent.setAction(Intent.ACTION_VIEW);  
									        Uri content_url = Uri.parse(URLConfig.WEBSITE + "reg.php");   
									        intent.setData(content_url);            
									        startActivity(intent);
										}
										return;
									}
									//点击确定下载
									if (!NetUtil.hasNetwork(context)) {
										LoadingTip.showToast(context, "请连接网络！");
										return;
									}
									downLoadData(account_txt, pwd_txt);
								}
							});
							builder.setCancelable(false);
							builder.create().show();
						}
					});
				}
			}
		});
    	builder.setNegativeButton("取消", null);
    	builder.create().show();
    }
    
    
    /**
     * 下载数据
     * @param account 帐号
     * @param pwd 密码
     */
    private void downLoadData(final String account, final String pwd) {
    	new Thread() {
    		@Override
    		public void run() {
    			// TODO Auto-generated method stub
    			getActivity().runOnUiThread(new Runnable() {
    				@Override
    				public void run() {
    					// TODO Auto-generated method stub
    					LoadingTip.showDialog(context, "正在下载备份数据...");
    				}
    			});
    			int count = 0;  //下载成功的数据量
    			String wrongInfo = null;  //出错信息
    			String info1 = DbOperator.getInstance(MyApplication.getInstance()).downLoadPatientFile(account, pwd);
    			try {
					if (info1 != null) {
						count = Integer.parseInt(info1);
					}
				} catch (NumberFormatException e) {
					// TODO: handle exception
					e.printStackTrace();
					wrongInfo = info1;
				}
    			
    			if (wrongInfo == null) {
    				String info2 = DbOperator.getInstance(MyApplication.getInstance()).downLoadDiseaseRecord(account, pwd);
        			try {
    					if (info2 != null) {
    						count += Integer.parseInt(info2);
    					}
    				} catch (NumberFormatException e) {
    					// TODO: handle exception
    					e.printStackTrace();
    					wrongInfo = info2;
    				}
				}
    			
    			finishDowload(count, wrongInfo);
    		}
    	}.start();
    }
    
    
    /**
     * 下载完成
     * @param count 下载数据量
     * @param wrongInfo 出错信息
     */
    private void finishDowload(final int count, final String wrongInfo) {
    	getActivity().runOnUiThread(new Runnable() {					
			@Override
			public void run() {
				// TODO Auto-generated method stub
				LoadingTip.hideDialog();
				String infoStr = wrongInfo != null ? (wrongInfo.endsWith("18702537275") || wrongInfo.endsWith("18702613050")? wrongInfo : wrongInfo + "！") : "本次下载数据" + count + "条！";
				if (count > 0) {
					infoStr = "本次下载数据" + count + "条！";
				} else if (wrongInfo != null) {
					infoStr = wrongInfo;
				} else {
					infoStr = "本次下载数据0条！";
				}
				
				String special = "帐号未激活，点击确定前往医师谷网站进行注册！\n如需帮助请联系医师宝客服中心 18702537275 18702613050";
				if (infoStr.startsWith(special) || special.equals(infoStr)) {
					DialogHelper.showConfirmCancelDialog(getActivity(), infoStr, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface arg0, int arg1) {
							// TODO Auto-generated method stub
							Intent intent = new Intent();        
					        intent.setAction(Intent.ACTION_VIEW);  
					        Uri content_url = Uri.parse(URLConfig.WEBSITE + "reg.php");   
					        intent.setData(content_url);            
					        startActivity(intent);
						}
					});
				} else {
					DialogHelper.showConfirmDialog(getActivity(), infoStr);
				}
			}
		});
    }
	
	
    /**
     * 上传数据
     * @param account 帐号
     * @param pwd 密码
     */
	private void uploadData(final String account, final String pwd) {
		LoadingTip.showDialog(getActivity(), "正在收集要上传的数据...");
		new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				 List<LinkedHashMap<String, String>> patientData = DbOperator.getInstance(MyApplication.getInstance()).selectPatientFileChangedData();
				 
				 int successCount = 0;  //操作成功次数
				 String wrongInfo = null;  //错误信息
				 int totalCount = 0;  //要上传的总数据量
				 if (patientData != null && !patientData.isEmpty()) {
					 getActivity().runOnUiThread(new Runnable() {
							@Override
							public void run() {
								// TODO Auto-generated method stub
								LoadingTip.setDialogMessage("正在上传数据...");
							}
						});
					totalCount = patientData.size();
					String[] info1 = uploadPatientFile(patientData, account, pwd);
					
					if (info1[1] == null) {
						//上传患者档案时没有错误信息，下一步才会紧接着上传病历数据
						try {
							successCount = Integer.parseInt(info1[0]);
							List<LinkedHashMap<String, String>> diseaseRecordData = DbOperator.getInstance(MyApplication.getInstance())
									.selectDiseaseRecordChangedData();
							if (diseaseRecordData != null && !diseaseRecordData.isEmpty()) {
								//上传病历数据
								totalCount += diseaseRecordData.size();
								String[] info2 = uploadDiseaseRecord(diseaseRecordData, account, pwd);
								if (info2[1] == null) {
									//没有出错信息
									successCount += Integer.parseInt(info2[0]);
								} else if (successCount <= 0) {
									successCount = -1;
									wrongInfo = info2[1];
								}
							}
						} catch (NumberFormatException e) {
							// TODO: handle exception
							e.printStackTrace();
						}
					} else {
						//上传患者档案时有错误信息
						successCount = -1;
						wrongInfo = info1[1];
					}
					 uploadFinish(totalCount, successCount, wrongInfo);
					 
				 } else {
					 List<LinkedHashMap<String, String>> diseaseRecordData = DbOperator.getInstance(MyApplication.getInstance())
								.selectDiseaseRecordChangedData();
					 if (diseaseRecordData != null && !diseaseRecordData.isEmpty()) {
						 getActivity().runOnUiThread(new Runnable() {
								@Override
								public void run() {
									// TODO Auto-generated method stub
									LoadingTip.setDialogMessage("正在上传数据...");
								}
							});
						 totalCount = diseaseRecordData.size();
						 String[] info2 = uploadDiseaseRecord(diseaseRecordData, account, pwd);
						 if (info2[1] == null) {
							try {
								successCount = Integer.parseInt(info2[0]);
							} catch (NumberFormatException e) {
								// TODO: handle exception
								e.printStackTrace();
							}
						} else {
							successCount = -1;
							wrongInfo = info2[1];
						}
						 uploadFinish(totalCount, successCount, wrongInfo);
						 
					} else {
						//没有数据变动
						 getActivity().runOnUiThread(new Runnable() {
								@Override
								public void run() {
									// TODO Auto-generated method stub
									LoadingTip.hideDialog();
									DialogHelper.showConfirmDialog(getActivity(), "没有新数据可上传！");
								}
							});
					}  
				}
			}
		}).start();
	}
	
	
	/**
	 * 上传任务完成
	 * @param dataCount 任务的数量量
	 * @param successCount 任务的成功量
	 * @param wrongInfo 错误信息
	 */
	private void uploadFinish(final int dataCount, final int successCount, final String wrongInfo) {
		getActivity().runOnUiThread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				LoadingTip.hideDialog();
				String infoStr;
				if (wrongInfo != null) {
					infoStr = wrongInfo.endsWith("18702537275") || wrongInfo.endsWith("18702613050") ? wrongInfo : wrongInfo + "！";
				} else {
					infoStr = "总共" + dataCount +"条数据，上传成功" + successCount + "条！";
				}
				
				String special = "帐号未激活，点击确定前往医师谷网站进行注册！\n如需帮助请联系医师宝客服中心 18702537275 18702613050";
				if (infoStr.startsWith(special) || special.equals(infoStr)) {
					DialogHelper.showConfirmCancelDialog(getActivity(), infoStr, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface arg0, int arg1) {
							// TODO Auto-generated method stub
							Intent intent = new Intent();        
					        intent.setAction(Intent.ACTION_VIEW);  
					        Uri content_url = Uri.parse(URLConfig.WEBSITE + "reg.php");   
					        intent.setData(content_url);            
					        startActivity(intent);
						}
					});
				} else {
					DialogHelper.showConfirmDialog(getActivity(), infoStr);
				}
			}
		});
	}
	
	
	/**
	 * 上传患者档案
	 * @param data
	 * @param account 帐号
     * @param pwd 密码
	 * @return 操作成功的次数(-1表示帐号验证有问题且一次操作都没成功)、出错信息
	 */
	private String[] uploadPatientFile(List<LinkedHashMap<String, String>> data, String account, String pwd) {
		int successCount = 0;  //操作成功的次数
		String wrongInfo = null;  //出错信息
		for (LinkedHashMap<String, String> map : data) {
			if (!NetUtil.hasNetwork(MyApplication.getInstance())) {
				break;
			}
			
			String[] idAndJson = field2json(map);
			if (idAndJson[0] == null || idAndJson[0].trim().length() <= 0) {
				//没有本地id的话则略过
				continue;
			}
			
			HashMap<String, String> params = new HashMap<String, String>();
			params.put("account", account);
			params.put("pwd", pwd);
			params.put("serial_number", FileHelper.getImieStatus(MyApplication.getInstance()));
			params.put("action", idAndJson[2]);
			if ("add".equals(idAndJson[2])) {
				//添加操作
				params.put("data", idAndJson[3]);
			} else if ("modify".equals(idAndJson[2])) {
				//修改操作
				params.put("data", idAndJson[3]);
				params.put("id", idAndJson[1]);
			} else if ("delete".equals(idAndJson[2])) {
				//删除操作
				params.put("id", idAndJson[1]);
			} else {
				continue;
			}
			
			RequestParams request = new RequestParams(URLConfig.PATIENT_FILE_URL, MyApplication.getInstance(), params, String.class);
			String result = GetDataThread.getInstance(MyApplication.getInstance()).postImg(request);
			
			if (result == null || result.trim().length() <= 0 || "不存在该账户".equals(result) || "账号已过有效期！请充值或者联系客服".equals(result) ||
					"账号未激活请注册".equals(result) || "用户名或密码错误".equals(result)  || "平板序列号错误".equals(result)) {
				//帐号验证有问题
				if (successCount <= 0) {
					successCount = -1;
					//一次操作都没有成功才会对外提供出错信息
					if (result == null || result.trim().length() <= 0) {
						wrongInfo = "本次上传不成功，请再次上传";
					} else if ("不存在该账户".equals(result) || "平板序列号错误".equals(result) || "用户名或密码错误".equals(result)) {
						wrongInfo = "请输入正确的密码";
					} else if ("账号已过有效期！请充值或者联系客服".equals(result)) {
						wrongInfo = "帐号已过有效期！请充值！\n充值电话：医师宝客服中心 18702537275 18702613050";
					} else if ("账号未激活请注册".equals(result)) {
						wrongInfo = "帐号未激活，点击确定前往医师谷网站进行注册！\n如需帮助请联系医师宝客服中心 18702537275 18702613050";
					} else {
						wrongInfo = "本次上传不成功，请再次上传";
					}
				}
				break;
			}
			
			if ("add".equals(idAndJson[2])) {
				try {
					int id = Integer.parseInt(result);
					if (id > 0) {
						//添加成功，从服务端返回的id
						ContentValues values = new ContentValues();
						values.put("_cid", id);
						values.put("_operation", ConstConfig.OPERATION_NULL);
						int row = DbOperator.getInstance(MyApplication.getInstance()).updateData(ConstConfig.PATIENT_FILE_TABLE, values, idAndJson[0]);
						if (row > 0) {
							successCount++;
						} 
					}
				} catch (NumberFormatException e) {
					// TODO: handle exception
					e.printStackTrace();
				}
				
			} else if ("modify".equals(idAndJson[2])) {
				if ("1".equals(result)) {
					//修改成功
					ContentValues values = new ContentValues();
					values.put("_operation", ConstConfig.OPERATION_NULL);
					int row = DbOperator.getInstance(MyApplication.getInstance()).updateData(ConstConfig.PATIENT_FILE_TABLE, values, idAndJson[0]);
					if (row > 0) {
						successCount++;
					} 
				}
			} else if ("delete".equals(idAndJson[2])) {
				if ("1".equals(result)) {
					//删除成功
					ContentValues values = new ContentValues();
					int row = DbOperator.getInstance(MyApplication.getInstance()).deleteData(ConstConfig.DELETED_PATIENT_FILE_TABLE, idAndJson[0]);
					if (row > 0) {
						successCount++;
					} 
				}
			}
		}
		return new String[]{String.valueOf(successCount), wrongInfo};
	}
	
	
	/**
	 * 上传病历资料
	 * @param data
	 * @param account 帐号
     * @param pwd 密码
	 * @return 操作成功的次数(-1表示帐号验证有问题且一次操作都没成功)、出错信息
	 */
	private String[] uploadDiseaseRecord(List<LinkedHashMap<String, String>> data, String account, String pwd) {
		int successCount = 0;  //操作成功的次数
		String wrongInfo = null;  //出错信息
		for (LinkedHashMap<String, String> map : data) {
			if (!NetUtil.hasNetwork(MyApplication.getInstance())) {
				break;
			}
			
			String[] idAndJson = field2json(map);
			if (idAndJson[0] == null || idAndJson[0].trim().length() <= 0) {
				//没有本地id的话则略过
				continue;
			}
			
			HashMap<String, String> params = new HashMap<String, String>();
			params.put("account", account);
			params.put("pwd", pwd);
			params.put("serial_number", FileHelper.getImieStatus(MyApplication.getInstance()));
			params.put("action", idAndJson[2]);
			if ("add".equals(idAndJson[2])) {
				//添加操作
				params.put("data", idAndJson[3]);
				if (idAndJson[4] != null && idAndJson[4].trim().length() > 0) {
					String[] picArray = idAndJson[4].split(ConstConfig.IMAGE_SPLIT);
					if (picArray != null) {
						for (int i = 0; i < picArray.length; i++) {
							params.put("pic" + (i + 1), picArray[i]);
						}
					}
				}
			} else if ("modify".equals(idAndJson[2])) {
				//修改操作
				params.put("data", idAndJson[3]);
				params.put("id", idAndJson[1]);
				if (idAndJson[4] != null && idAndJson[4].trim().length() > 0) {
					String[] picArray = idAndJson[4].split(ConstConfig.IMAGE_SPLIT);
					if (picArray != null) {
						for (int i = 0; i < picArray.length; i++) {
							params.put("pic" + (i + 1), picArray[i]);
						}
					}
				}
			} else if ("delete".equals(idAndJson[2])) {
				//删除操作
				params.put("id", idAndJson[1]);
			} else {
				continue;
			}
			
			RequestParams request = new RequestParams(URLConfig.DISEASE_RECORD_URL, MyApplication.getInstance(), params, String.class);
			String result = GetDataThread.getInstance(MyApplication.getInstance()).postImg(request);
			if (result == null || result.trim().length() <= 0 || "不存在该账户".equals(result) || "账号已过有效期！请充值或者联系客服".equals(result) ||
					"账号未激活请注册".equals(result) || "用户名或密码错误".equals(result)  || "平板序列号错误".equals(result)) {
				//帐号验证有问题
				if (successCount <= 0) {
					successCount = -1;
					//一次操作都没有成功才会对外提供出错信息
					if (result == null || result.trim().length() <= 0) {
						wrongInfo = "本次上传不成功，请再次上传";
					} else if ("不存在该账户".equals(result)  || "平板序列号错误".equals(result) || "用户名或密码错误".equals(result)) {
						wrongInfo = "请输入正确的密码";
					} else if ("账号已过有效期！请充值或者联系客服".equals(result)) {
						wrongInfo = "帐号已过有效期！请充值！\n充值电话：医师宝客服中心 18702537275 18702613050";
					} else if ("账号未激活请注册".equals(result)) {
						wrongInfo = "帐号未激活，点击确定前往医师谷网站进行注册！\n如需帮助请联系医师宝客服中心 18702537275 18702613050";
					} else {
						wrongInfo = "本次上传不成功，请再次上传";
					}
				}
				break;
			}
			
			if ("add".equals(idAndJson[2])) {
				try {
					int id = Integer.parseInt(result);
					if (id > 0) {
						//添加成功，从服务端返回的id
						ContentValues values = new ContentValues();
						values.put("_cid", id);
						values.put("_operation", ConstConfig.OPERATION_NULL);
						int row = DbOperator.getInstance(MyApplication.getInstance()).updateData(ConstConfig.DISEASE_RECORD_TABLE, values, idAndJson[0]);
						if (row > 0) {
							successCount++;
						} 
					}
				} catch (NumberFormatException e) {
					// TODO: handle exception
					e.printStackTrace();
				}
				
			} else if ("modify".equals(idAndJson[2])) {
				if ("1".equals(result)) {
					//修改成功
					ContentValues values = new ContentValues();
					values.put("_operation", ConstConfig.OPERATION_NULL);
					int row = DbOperator.getInstance(MyApplication.getInstance()).updateData(ConstConfig.DISEASE_RECORD_TABLE, values, idAndJson[0]);
					if (row > 0) {
						successCount++;
					} 
				}
			} else if ("delete".equals(idAndJson[2])) {
				if ("1".equals(result)) {
					//删除成功
					ContentValues values = new ContentValues();
					int row = DbOperator.getInstance(MyApplication.getInstance()).deleteData(ConstConfig.DELETED_DISEASE_RECORD_TABLE, idAndJson[0]);
					if (row > 0) {
						successCount++;
					}
				}
			}
		}
		return new String[]{String.valueOf(successCount), wrongInfo};
	}
	
	
	/**
	 * key-value转换成json
	 * @param map key-value对，必须至少要有一个key-value对
	 * @return 本地id、服务端id、要执行的操作、json和图片路径
	 */
	private String[] field2json(LinkedHashMap<String, String> map) {
		StringBuilder sb = new StringBuilder();
		String localId = null, serverId = null, action = null, pic = null;
		sb.append("{");
		for (Entry<String, String> entry : map.entrySet()) {
			if ("local_id".equals(entry.getKey())) {
				localId = entry.getValue();
				continue;
			} else if ("id".equals(entry.getKey())) {
				serverId = entry.getValue();
				continue;
			} else if ("action".equals(entry.getKey())) {
				action = entry.getValue();
				continue;
			} else if ("pic".equals(entry.getKey())) {
				pic = entry.getValue();
				continue;
			}
			
			sb.append("\"");
			sb.append(entry.getKey());
			sb.append("\"");
			sb.append(":");
			sb.append("\"");
			String value = entry.getValue();
			if (value != null) {
				//消除换行符
//				value = value.replaceAll("\r\n", "");
//				value = value.replaceAll("\n", "");
				value = Html.fromHtml(value).toString();
			}
			sb.append(value == null ? "" : value);
			sb.append("\"");
			sb.append(",");
		}
		sb.deleteCharAt(sb.length() - 1);  //删除最后一个多余的逗号
		sb.append("}");
		return new String[]{localId, serverId, action, sb.toString(), pic};
	}
	
	
	
}
